<?php

namespace App\Http\Controllers;

use zgldh\QiniuStorage\QiniuStorage;

use App\Models\Column;
use App\Models\Area;
use App\Models\Site;

use Cache;
use Session;
use Illuminate\Support\Str;
use Illuminate\Http\Request;

class WebSiteController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index(Request $request)
    {
        //
        $sites  = Site::where('user_id', $request->user()->id)->select('id','name','column_id','state','updated_at')->orderBy('id', 'desc')->get()->toJson();
        return view('home.website.index',compact('sites'));
    }
    public function create()
    {
        //
        $area   = Area::get();
        $column = Column::where('type',0)->where('parent_id',0)->get();
        return view('home.website.create',compact('column','area'));
    }
    public function store(Request $request)
    {
        $site   = Site::where('url','like',$request->get('url'))->first();
        if ($site) {
            return response()->json([
                'code' => 'error',
                'data' => '您提交的网站已经存在!',
            ],200);
        }

        $count  = Site::where('user_id', $request->user()->id)->count();
        if ($count > 2) {
            return response()->json([
                'code' => 'error',
                'data' => '您的免费额度已经使用完毕!',
            ],200);
        }

        $file_name  = 'files/'.$request->get('url').md5(time()).'.ico';
        $flight = new Site;
        $flight->user_id = $request->user()->id;
        $flight->name = $request->get('name');
        $flight->url = $request->get('url');
        $flight->column_id = $request->get('catid')[1];
        $flight->area_id = $request->get('areaid')[0];
        $flight->keywords = $request->get('keywords');
        $flight->description = $request->get('description');
        $flight->icon = $file_name;
        $flight->content = collect($request->get('data'))->toArray();
        $flight->save();

        if($flight->id){
            $disk       = QiniuStorage::disk('qiniu');
            $contents   = base64_decode($request->get('icon'));
            $disk->put($file_name,$contents);
        }
        return response()->json([
            'code'  => 'success',
            'data'  => '您的网站已经提交成功,请等待审核!',
            'url'   => route('website.index'),
        ],200);
    }
    public function show($id)
    {
        //
    }
    public function edit($id)
    {
        //
        $site   = Site::where('id',$id)->first();
        $area   = Area::get();
        $column = Column::where('type',0)->where('parent_id',0)->get();
        return view('home.website.edit',compact('column','area','site'));
    }
    public function update(Request $request, $id)
    {
        //
    }
    public function destroy($id)
    {
        //
    }
    public function classify(Request $request)
    {
        $column = Column::where('type',0)->where('parent_id',$request->get('parent_id'))->get();
        $str  = '';
        foreach ($column as $v){
            $str .= '<option value="'.$v->id.'">'.$v->title.'</option>\n';
        }
        return response()->json(['code' => 'success','data' => $str ,'url' => ''],200);
    }
    public function img()
    {
        return response()->json([
            'code' => 0,
            'data' => [
                'src' => ''
            ],
            'url' => ''
        ],200);
    }
    public function claimGet(Request $request){
        $get    = $request->session()->get('url');
        if(!empty($get)) {
            $url	= $get;
            $token  = Cache::get('url_verification_'.$url);
        }
        return view('home.website.claim',compact('url','token'));
    }
    public function claimPost(Request $request,$action)
    {
        if($action == 'host'){
            $site   = Site::where('url','like',$request->get('url'))->first();
            if($site){
                $request->session()->put('url', $site->url);
                // 使用 Laravel 内置的 Str 类生成随机字符串的函数，参数就是要生成的字符串长度
                $token = Str::random(30);
                // 往缓存中写入这个随机字符串，有效时间为 30 分钟。
                Cache::set('url_verification_'.$site->url, $token, 30);
                return response()->json([
                    'data' => '准备一下3秒后,进行验证!……',
                    'code' => 1,
                    'url' => url('website/claim')
                ],200);
            }else{
                return response()->json([
                    'data' => '此网站未添加,请添加!……',
                    'code' => 0
                ],200);
            }
        }
        if($action == 'file')
        {
            $url    = $request->session()->get('url');
            $path   = 'http://'.$url.'/'.$url.'.txt';
            $token  = Cache::get('url_verification_'.$url);
            $res    = $this->get_txt($path);
            if($res){
                if($res == $token){
                    Site::where('url','like', $url)->update(['user_id' => $request->user()->id]);
                    Cache::forget('url_verification_'.$url);
                    $request->session()->forget('url');
                    return response()->json(['data' => '核对成功!正在为您跳转到对应网址!……', 'code' => 1, 'url' => route('website.index')],200);
                }
                return response()->json(['data' => '验证代码错误或验证文件未放置!……', 'code' => 0],200);
            }else{
                return response()->json(['data' => '验证代码错误或验证文件未放置!……', 'code' => 0],200);
            }
        }
        if($action == 'html')
        {
            $url    = $request->session()->get('url');
            $path   = 'http://'.$url;
            $token  = Cache::get('url_verification_'.$url);
            $res    = get_meta_tags($path);
            if($res){
                if(array_key_exists('check-domain',$res)){
                    if($res['check-domain'] == $token){
                        Site::where('url','like', $url)->update(['user_id' => $request->user()->id]);
                        Cache::forget('url_verification_'.$url);
                        $request->session()->forget('url');
                        return response()->json(['data' => '核对成功!正在为您跳转到对应网址!……', 'code' => 1, 'url' => route('website.index')],200);
                    }
                    return response()->json(['data' => '验证失败请检查代码放置是否正确!……', 'code' => 0],200);
                }
                return response()->json(['data' => '验证失败请检查代码放置是否正确!……', 'code' => 0],200);
            }else{
                return response()->json(['data' => '验证失败请检查代码放置是否正确!……', 'code' => 0],200);
            }
        }
        return [];
    }
    function get_txt($url){
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER,0);
        // 3. 执行并获取HTML文档内容
        $output     = curl_exec($ch);
        $info    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 4. 释放curl句柄
        curl_close($ch);
        if($info != 200){
            return false;
        }
        if($output === FALSE ){
            return false;
        }
        return $output;
    }
    public function claimDown(){
        $url    = session('url');
        $token  = Cache::get('url_verification_'.$url);
        $filename= $url.'.txt';
        header("Accept-Ranges:bytes");
        header("Content-Type:text/txt");
        header("Content-Disposition:attachment;filename=".$filename);
        echo $token;
    }
}
